<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>使用XHR封装ajax请求参数</title>
</head>
<body>
  <div>
    <button onclick="testGet()">发送GET请求</button>
    <button onclick="testPost()">发送POST请求</button>
    <button onclick="testPut()">发送PUT请求</button>
    <button onclick="testDelete()">发送Delete请求</button>
  </div>

  <script>
   
    function testGet() {
      axios({
        // url: 'http://localhost:3000/posts',
        url: 'http://localhost:3000/posts2',
        method: 'GET',
        params: {
          id: 1,
          title: 'abc'
        }
      }).then(
        response => {
          console.log(response)
        },
        error => {
          alert(error.message)
        }
      )
    }

    function testPost() {
      axios({
        url: 'http://localhost:3000/posts',
        method: 'POST',
        data: {
          "title": "json-server---",
          "author": "typicode---"
        }
      }).then(
        response => {
          console.log(response)
        },
        error => {
          alert(error.message)
        }
      )
    }

    function testPut() {
      axios({
        url: 'http://localhost:3000/posts/1',
        method: 'put',
        data: {
          "title": "json-server+++",
          "author": "typicode+++"
        }
      }).then(
        response => {
          console.log(response)
        },
        error => {
          alert(error.message)
        }
      )
    }

    function testDelete() {
      axios({
        url: 'http://localhost:3000/posts/3',
        method: 'delete'
      }).then(
        response => {
          console.log(response)
        },
        error => {
          alert(error.message)
        }
      )
    }

    /**
     * url 请求地址
     * method 请求方式GET/POST/PUT/DELETE
     * params GET/DELETE请求的参数
     * data POST/DELETE请求的参数
     * 
     */

    function axios({ // 该函数的参数使用解构赋值
      url,
      method = 'GET',
      params = {},
      data = {}
    }) {
      // 返回一个promise对象
      return new Promise((resolve, reject) => { // 执行异步操作

        method = method.toUpperCase()
        // 拼接完整url
        let queryString = ''
        Object.keys(params).forEach(key => {
          queryString += `${key}=${params[key]}&`
        })
        if (queryString) {
          // 去除最后的&
          queryString = queryString.substring(0, queryString.length - 1)
          // 接到url
          url += '?' + queryString
        }
        // 创建xhr对象
        const xhr = new XMLHttpRequest()
        // 初始化请求
        xhr.open(method, url, true)
        // 发送请求
        if (method === 'GET' || method === 'DELETE') {
          xhr.send()
        } else if (method === 'POST' || method === 'PUT') {
          xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8') // 告诉服务器请求体的格式是json
          xhr.send(JSON.stringify(data)) // 发送JSON字符串格式请求体参数
        }

        // 绑定readystate状态改变的监听
        xhr.onreadystatechange = function () {
          // 如果请求没有完成, 直接结束
          if (xhr.readyState !== 4) {
            return
          }
          // 如果响应状态码在[200, 300)之间代表成功, 否则失败
          const { status, statusText } = xhr
          if (status >= 200 && status < 300) { // 如果请求成功，调用resolve
            // 准备结果数据对象response
            const response = {
              data: JSON.parse(xhr.response),
              status,
              statusText
            }
            resolve(response)
          } else { // 如果请求失败了, 调用reject()
            reject(new Error('request error status is ' + status))
          }
        }
      })
    }
  </script>
</body>
</html>